/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.LazyloadListActivity;
import com.mol.market.common.widget.LoadingDrawable;

/**
 * 标签列表页
 * @author Chaos	
 * @since 0.9.6
 * @date 2012-10-17
 */
public class TagsListActivity extends LazyloadListActivity implements ApiAsyncTask.ApiRequestListener
                ,OnClickListener,OnItemClickListener{

    public static final String TAGS_ID   = "tagsId";
    public static final String TAGS_NAME = "tagsName";
    
    private AppListAdapter mRecommendAdapter;
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;
    
    private String mTagsId   = null;
    private String mTagsName = null;
    
    private int mTotalSize = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {

        HashMap<String, Object> result = (HashMap<String, Object>) obj;
        
        if (mTotalSize <= 0) {
          // 获取总大小
          mTotalSize = (Integer) result.get(Constants.KEY_TOTAL_SIZE);
        }
        mRecommendAdapter.addDataList((ArrayList<HashMap<String, Object>>) result
                .get(Constants.KEY_PRODUCT_LIST));
        setLoadResult(true);
    }

    @Override
    public void onError(int method, int statusCode) {
        mNoData.setVisibility(View.VISIBLE);
        mProgress.setVisibility(View.GONE);
        setLoadResult(false);
    }
    
    private void initTopBar(String title) {
        TopBar.createTopBar(mSession, this, 
                new View[] { 
                    findViewById(R.id.top_bar_title),
                    findViewById(R.id.top_bar_search),}, 
                new int[] { 
                    View.VISIBLE, 
                    View.VISIBLE,
                }, getString(R.string.tags_title, title));
    }
    
    @Override
    public void onClick(View v) {
        // 重试
        mProgress.setVisibility(View.VISIBLE);
        mNoData.setVisibility(View.GONE);
        lazyload();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
        case android.R.id.list:

            @SuppressWarnings("unchecked")
            HashMap<String, Object> item = (HashMap<String, Object>) parent.getAdapter()
                    .getItem(position); 
            String pid = (String) item.get(Constants.KEY_PRODUCT_ID);
            boolean isCpa = (Boolean) item.get(Constants.KEY_PRODUCT_IS_STAR);
            Intent detailIntent = new Intent(getApplicationContext(), com.mol.market.ui_v4.ProductDetailActivity.class);
            detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
            
            if (isCpa) {
                // 统计推荐位
                Utils.trackEvent(
                        getApplicationContext(),
                        Constants.GROUP_2,
                        String.format(Constants.EVENT_CLICK_RECOMMEND,
                                item.get(Constants.KEY_PRODUCT_NAME), position));
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_RECOMMEND, true);
            }
            startActivity(detailIntent);
            
            break;

        default:

            break;
        }        
    }

    @Override
    public boolean doInitView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_tags_list);
        
        mTagsId = getIntent().getStringExtra(TAGS_ID);
        mTagsName = getIntent().getStringExtra(TAGS_NAME);
        
        if(mTagsId == null || mTagsName == null){
            return false;
        }
        
        initTopBar(mTagsName);
        
        initView();
        
        lazyload();
        
        return true;
    }
    
    private void initView(){
        mList = (ListView) findViewById(android.R.id.list);
        mLoading = (FrameLayout) findViewById(R.id.loading);
        mProgress = (ProgressBar) findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        mList.setEmptyView(mLoading);
    }

    @Override
    public void doLazyload() {
//        MarketAPI.getCategoryTagsDetails(getApplicationContext(), this, getItemsPerPage(), getStartIndex(), mTagsId);
    }

    @Override
    public AppListAdapter doInitListAdapter() {
        mRecommendAdapter = new AppListAdapter(
                getApplicationContext(),
                null,
                R.layout.common_product_list_item, 
                new String[] {
                        Constants.KEY_PRODUCT_ICON_URL, 
                        Constants.KEY_PRODUCT_NAME,
                        Constants.KEY_PRODUCT_SUB_CATEGORY, 
                        Constants.KEY_PRODUCT_IS_STAR,
                        Constants.KEY_PRODUCT_SIZE, 
                        Constants.KEY_PRODUCT_DOWNLOAD }, 
                new int[] {
                        R.id.iv_logo, 
                        R.id.tv_name, 
                        R.id.tv_description, 
                        R.id.iv_star,
                        R.id.tv_size, 
                        R.id.tv_download });
        mRecommendAdapter.setActivity(getParent());
        
        mRecommendAdapter.setProductList();
        mList.setAdapter(mRecommendAdapter);
        mList.setOnItemClickListener(this);
        return mRecommendAdapter;
    }
    
    @Override
    protected int getItemCount() {
        return mTotalSize;
    }
    
}
